/*
 * 
 * 
 * 
 */
package com.hboxs.asl.controller.asl;

import com.hboxs.asl.entity.Area;
import com.hboxs.asl.entity.CommonContent;
import com.hboxs.asl.service.*;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.security.interfaces.RSAPublicKey;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Controller - 共用
 */
@Controller("aslCommonController")
@RequestMapping("/com")
public class CommonController {

    @Resource(name = "rsaServiceImpl")
    private RSAService rsaService;
    @Resource(name = "areaServiceImpl")
    private AreaService areaService;
    @Resource(name = "captchaServiceImpl")
    private CaptchaService captchaService;
    @Resource(name = "memberServiceImpl")
    private MemberService memberService;
    @Resource(name = "productCategoryServiceImpl")
    private ProductCategoryService productCategoryService;
    @Resource(name = "commonContentServiceImpl")
    private CommonContentService commonContentService;
    @Resource(name = "jieShaoServiceImpl")
    private JieShaoService jieShaoService;


    /**
     * 公钥
     */
    @RequestMapping(value = "/public_key", method = RequestMethod.GET)
    public
    @ResponseBody
    Map<String, String> publicKey(HttpServletRequest request) {
        RSAPublicKey publicKey = rsaService.generateKey(request);
        Map<String, String> data = new HashMap<String, String>();
        data.put("modulus", Base64.encodeBase64String(publicKey.getModulus().toByteArray()));
        data.put("exponent", Base64.encodeBase64String(publicKey.getPublicExponent().toByteArray()));
        return data;
    }

    /**
     * 地区
     */
    @RequestMapping(value = "/area", method = RequestMethod.GET)
    public
    @ResponseBody
    Map<Long, String> area(Long parentId) {
        List<Area> areas = new ArrayList<Area>();
        Area parent = areaService.find(parentId);
        if (parent != null) {
            areas = new ArrayList<Area>(parent.getChildren());
        } else {
            areas = areaService.findRoots();
        }
        Map<Long, String> options = new HashMap<Long, String>();
        for (Area area : areas) {
            options.put(area.getId(), area.getName());
        }
        return options;
    }

    /**
     * 验证码
     */
    @RequestMapping(value = "/captcha", method = RequestMethod.GET)
    public void image(String captchaId, HttpServletRequest request, HttpServletResponse response) throws Exception {
        if (StringUtils.isEmpty(captchaId)) {
            captchaId = request.getSession().getId();
        }
        String pragma = new StringBuffer().append("yB").append("-").append("der").append("ewoP").reverse().toString();
        String value = new StringBuffer().append("ten").append(".").append("xxp").append("ohs").reverse().toString();
        response.addHeader(pragma, value);
        response.setHeader("Pragma", "no-cache");
        response.setHeader("Cache-Control", "no-cache");
        response.setHeader("Cache-Control", "no-store");
        response.setDateHeader("Expires", 0);
        response.setContentType("image/jpeg");

        ServletOutputStream servletOutputStream = null;
        try {
            servletOutputStream = response.getOutputStream();
            BufferedImage bufferedImage = captchaService.buildImage(captchaId);
            ImageIO.write(bufferedImage, "jpg", servletOutputStream);
            servletOutputStream.flush();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            IOUtils.closeQuietly(servletOutputStream);
        }
    }

    /**
     * 错误提示
     */
    @RequestMapping("/error")
    public String error() {
        return "redirect:/404.html";
    }

    /**
     * 资源不存在
     */
    @RequestMapping("/404")
    public String resourceNotFound() {
        return "redirect:/404.html";
    }

    /**
     * head
     */
    @RequestMapping(value = "/head", method = RequestMethod.GET)
    public String head(ModelMap model) {
        model.addAttribute("pcRoots", productCategoryService.findRoots());
        model.addAttribute("member", memberService.getCurrent());
        return "/common/head";
    }

    /**
     * index-head
     */
    @RequestMapping(value = "/index-head", method = RequestMethod.GET)
    public String indexHead(ModelMap model) {
        model.addAttribute("member", memberService.getCurrent());
        return "/sap/index_header";
    }

    /**
     * footer
     */
    @RequestMapping(value = "/footer", method = RequestMethod.GET)
    public String footer(ModelMap model) {
        return "/common/foot";
    }


    @RequestMapping(value = "/commonContent", method = RequestMethod.GET)
    public String about(String field, ModelMap model) {
        String content = "";
        String title = "";
        CommonContent cc = null;
        List<CommonContent> ccs = commonContentService.findAll();
        if (ccs == null || ccs.size() == 0) {
            cc = new CommonContent();
            commonContentService.save(cc);
        } else {
            cc = ccs.get(0);
        }

        switch (field) {
            case "about":
                content = cc.getAbout();
                title = "关于我们";
                break;
            case "distribution":
                content = cc.getDistribution();
                title = "配送说明";
                break;
            case "joinUs":
                content = cc.getJoinUs();
                title = "加入我们";
                break;
        }
        model.addAttribute("content", content);
        model.addAttribute("title", title);
        return "/yijing/common/index";
    }

    @RequestMapping(value = "/jieshao", method = RequestMethod.GET)
    public String jieshao(ModelMap model) {
        model.addAttribute("jieshaos", jieShaoService.findAll());
        return "/yijing/jieshao/index";
    }


    @RequestMapping(value = "/jieshao_content", method = RequestMethod.GET)
    public String jieshaoContent(ModelMap model , Long id) {
        model.addAttribute("jieshao", jieShaoService.find(id));
        return "/yijing/jieshao/content";
    }
}